/*
 * Copyright (c) 2023 Cshoo Org. All Rights Reserved.
 */

package org.cshoo.tattoo.authorize.domain.repository;

import org.cshoo.tattoo.authorize.domain.po.User;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.CrudRepository;
import org.springframework.data.repository.query.Param;

import javax.transaction.Transactional;
import java.util.List;

/**
 * @author 杨翼
 * @since 1.0
 */
public interface IUserRepository extends CrudRepository<User, Long> {

    /**
     * 分页查询角色数据
     *
     * @param pageable 分页信息
     * @return 用户
     */
    Page<User> findAll(Pageable pageable);

    User findUserByUsername(String username);

    /**
     * 修改用户信息
     *
     * @param user 用户
     */
    @Query("update User user set user.name = :#{#user.name}, user.lastUpdatedBy = :#{#user.lastUpdatedBy}, user.lastUpdateTime = :#{#user.lastUpdateTime} where user.id = :#{#user.id}")
    @Transactional
    @Modifying
    void updateUser(User user);

    @Query(value = "select user from User user left join GroupUserRelation gur on user.id = gur.userId where gur.groupId = ?1")
    List<User> findUsersByGroupId(Long groupId);

    @Query(value = "select * from t_user t where t.name like CONCAT('%',?1,'%') or t.username like CONCAT('%',?1,'%')", nativeQuery = true)
    List<User> findUserByName(String name);

    @Query(value = "insert into r_user_menu (user_id,menu_id) values(:#{#userId},:#{#menuId})", nativeQuery = true)
    @Modifying
    @Transactional
    void authorizeMenu(@Param("userId") Long userId, @Param("menuId") Long menuId);

    @Query(value = "delete from r_user_menu where user_id = :#{#userId} and menu_id = :#{#menuId}", nativeQuery = true)
    @Modifying
    @Transactional
    void cancelMenuAuthority(@Param("userId") Long userId, @Param("menuId") Long menuId);

    @Query(value = "insert into r_user_button (user_id,button_id) values(:#{#userId},:#{#buttonId})", nativeQuery = true)
    @Modifying
    @Transactional
    void authorizeButton(@Param("userId") Long userId, @Param("buttonId") Long buttonId);

}
